import redis
import orjson
import fire

REDIS_URL = '43.198.246.1'
REDIS_PORT = 18379


r = redis.Redis(host=REDIS_URL,port=REDIS_PORT,password="")

def send_order(account:str,qid:str,securityID:str,orderType:str,orderQty:int,price:float,side:str,openClose:str,algo:dict=None):
    if str(orderType) not in ["1","2"]: # 1:市价 2:限价
        raise ValueError("Incorrect value for orderType")
    if str(side) not in ["1","2","5"]: # 1:买 2:卖 5:卖空
        raise ValueError("Incorrect value for side")
    if str(openClose) not in ["O","C"]: # O:开 C:平
        raise ValueError("Incorrect value for openClose")
    order = {
            "type":"new",
            "account":account,
            "qid":str(qid),
            "securityID":securityID,
            "side":f'{side}',
            "orderType":f'{orderType}',
            "orderQty":orderQty,
            "price":price,
            "openClose":f'{openClose}',
            "sym":securityID
            }
    if algo:
        order['algo'] = algo
    r.publish('newOrder',orjson.dumps(order))


def cancel_order(account:str,securityID:str,side:str,ClOrdID:str,qid:str):
    if str(side) not in ["1","2"]:
        raise ValueError("Incorrect value for side")
    order = {
        "type":"cancel",
        "account":account,
        "securityID":securityID,
        "side":str(side),
        "ClOrdID":str(ClOrdID),
        "qid":str(qid),
        "sym":securityID
            }
    r.publish("newOrder",orjson.dumps(order))

def amend_order(account:str,ClOrdID:str,orderType:str,securityID:str,side:str,price:float,orderQty:int,openClose:str,qid:str):
    if str(orderType) not in ["1","2"]:
        raise ValueError("Incorrect value for orderType")
    if str(side) not in ["1","2","5"]:
        raise ValueError("Incorrect value for side")
    if str(openClose) not in ["O","C"]:
        raise ValueError("Incorrect value for openClose")
    order = {
        "type":"replace",
        "account":account,
        "qid":str(qid),
        "ClOrdID":str(ClOrdID),
        "securityID":securityID,
        "side":str(side),
        "orderType":str(orderType),
        "orderQty":orderQty,
        "price":price,
        "side":str(side),
        "openClose":str(openClose),
        "sym":securityID
    }
    r.publish("newOrder",orjson.dumps(order))

if __name__ == "__main__":
    fire.Fire({"send":send_order,"cancel":cancel_order,"amend":amend_order})

